package com.maixun.lib_choosefile

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.maixun.lib_choosefile.entity.FileItem
import com.maixun.lib_choosefile.entity.LocalFileIm
import com.maixun.lib_choosefile.ui.preview.PreviewActivity
import java.lang.ref.WeakReference

/**
 * @author：Lmoumou
 * @date：2020/10/9
 */
class LocalFileSelect {

    private var mContext: WeakReference<Activity>? = null
    private var mFragment: WeakReference<Fragment>? = null

    constructor(activity: Activity) : this(activity, null)
    constructor(fragment: Fragment) : this(fragment.activity, fragment)
    constructor(activity: Activity?, fragment: Fragment?) {
        activity?.let {
            mContext = WeakReference(activity)
        }
        fragment?.let {
            mFragment = WeakReference(fragment)
        }
    }

    companion object {
        fun from(activity: Activity): LocalFileSelect {
            return LocalFileSelect(activity)
        }

        fun from(fragment: Fragment): LocalFileSelect {
            return LocalFileSelect(fragment)
        }

        fun obtainResult(data: Intent): ArrayList<LocalFileIm>? {
            return data.getParcelableArrayListExtra(LocalFileConst.EXTRA_RESULT_SELECTION)
        }
    }

    fun choose(): SelectionCreator {
        return SelectionCreator(this)
    }

    fun <T : FileItem> onPreView(data: T) {
        val activity = getActivity() ?: return
        val intent = Intent(activity, PreviewActivity::class.java).apply {
            val bundle = Bundle()
            bundle.putString(LocalFileConst.FILE_NAME, data.getFileName())
            bundle.putSerializable(LocalFileConst.FILE_TYPE2, data.getFileType())
            bundle.putString(LocalFileConst.FILE_PATH, data.getFilePath())
            bundle.putBoolean(LocalFileConst.LOCAL, data.isLocal())
            putExtras(bundle)
        }

        val fragment = getFragment()
        if (fragment != null) {
            fragment.startActivity(intent)
        } else {
            activity.startActivity(intent)
        }
    }

    fun getActivity(): Activity? {
        return mContext?.get()
    }

    fun getFragment(): Fragment? {
        return mFragment?.get()
    }
}